﻿using System;
using System.IO;

namespace dk.Helper.Base.Core
{
    public class AllyDataReader : IAllyDataReader
    {
        private readonly IPlayers players;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object"/> class.
        /// </summary>
        public AllyDataReader(IPlayers players)
        {
            this.players = players;
        }

        #region IAllyDataReader Members

        /// <summary>
        /// Creates the allies.
        /// </summary>
        /// <param name="datafile">The datafile.</param>
        /// <returns></returns>
        public IAllies CreateAllies(string datafile)
        {
            if (!File.Exists(datafile))
                return null;

            IAllyParser allyParser = new AllyParser();
            IAllies allies = new Allies();
            using (TextReader textReader = new StreamReader(datafile))
            {
                string data;
                while ((data = textReader.ReadLine()) != null)
                {
                    IAlly ally = allyParser.CreateAlly(data, players);
                    if (ally == null)
                    {
                        throw new InvalidOperationException("Failed to parse ally: " + data);
                    }
                    allies.AlliesByID.Add(ally.ID, ally);
                    allies.AlliesByTag.Add(ally.Tag, ally);
                }
            }
            return allies;
        }

        #endregion
    }
}